/**
 * index.js
 * @authors 杨兴洲（of2502）
 * @date    2017/6/20 0020 11:05
 * @version 1.0
 * @last-modify  杨兴洲（of2502）
 */
import {Router} from "express";
import logger from "../../util/logger";
import CONFIG from "../../config";
import UserService from "../../service/user-service";
import WxUserService from "../../service/weixin-user-service";
import MCService from "../../service/mc-service";
import WxAuthorizerService from "../../service/weixin-authorizer-service";

const router = Router();
const ADMIN_TOKEN = CONFIG.ADMIN_TOKEN || "!Shua1Shu2Ju3";
export default router;

function checkToken(req, res, next) {
    const {token} = req.query || req.body;
    if (token !== ADMIN_TOKEN) {
        const error = new Error();
        error["errcode"] = 88888;
        error["errmsg"] = "禁止访问!!!";
        return next(error);
    }

    next();
}

function checkFansParams(req, res, next) {
    const {userID} = req.query || req.body;
    if (!userID) {
        const error = new Error();
        error["errcode"] = 10001;
        error["errmsg"] = "缺少用户编号";
        return next(error);
    }
    next();
}

// 获取用户列表
router.get('/user', checkToken, (req, res, next) => {
    (async () => {
        try {
            const {page = 1, pageSize = 20} = req.query;
            const list = await UserService.getList(page, pageSize);
            res.status(200).json(list);
        } catch (error) {
            next(error);
        }
    })();
});

// 获取某个用户的粉丝列表
router.get('/fans', checkToken, (req, res, next) => {
    (async () => {
        try {
            const {next_openid, userID} = req.query;
            const access_token = await UserService.getAccessToken(userID);
            const list = await WxUserService.getList({access_token, next_openid});
            res.status(200).json(list);
        } catch (error) {
            next(error);
        }
    })();
});

router.get('/sync/fans/follow', [checkToken, checkFansParams], (req, res, next) => {
    (async () => {
        try {
            const {userID} = req.query;
            await MCService.batchAllFollow(userID);
            res.status(200).json({});
        } catch (error) {
            next(error);
        }
    })();
});
router.get('/sync/fans/unfollow', checkFansParams, (req, res, next) => {
    (async () => {
        try {
            const {userID} = req.query;
            await MCService.batchAllUnfollow(userID);
            res.status(200).json({});
        } catch (error) {
            next(error);
        }
    })();
});

/**
 * 重置API调用次数
 */
router.get('/reset', (req, res, next) => {
    (async () => {
        try {
            const {userID} = req.query;
            const access_token = await UserService.getAccessToken(userID);
            const {authorizer_appid} = await UserService.getInfo(userID);
            const data = await WxAuthorizerService.clearQuota({access_token, authorizer_appid});
            res.status(200).json(data);
        } catch (error) {
            next(error);
        }
    })();
});

// api接口不报错,输出json
router.use((err, req, res, next) => {
    logger.error("请求方法:", req.method, req.originalUrl);
    logger.error("请求参数:", req.method === "POST" ? req.body : req.query);
    logger.error("错误信息:", err);
    res.json(err);
});
